package com.eqs.enterprisequestionnaire.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eqs.enterprisequestionnaire.mapper.*;
import com.eqs.enterprisequestionnaire.model.pojo.*;
import com.eqs.enterprisequestionnaire.service.AnswerService;
import com.eqs.enterprisequestionnaire.service.HistoryService;
import com.eqs.enterprisequestionnaire.service.ResponseService;
import jakarta.annotation.Resource;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.eqs.enterprisequestionnaire.model.enums.QuestionEnum.*;

@Service
public class ResponseServiceImpl extends ServiceImpl<ResponseMapper, Response> implements ResponseService {

    @Resource
    private ResponseMapper responseMapper;
    @Resource
    private AnswerService answerService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private QuestionMapper questionMapper;
    @Resource
    private AnswerMapper answerMapper;
    @Resource
    private QuestionnaireMapper questionnaireMapper;
    public List<Response> selectAll(Response response){

        Map<String ,Object> params =new HashMap<>();
        params.put("questionnaire_id",response.getQuestionnaireId());
        params.put("user_id",response.getUserId());

        QueryWrapper<Response> queryWrapper= new QueryWrapper<Response>();

        queryWrapper.allEq( params,false);

        return list(queryWrapper);
    }


    public List<Response> selectAllResponse(Integer questionnaireId){
        Response response=new Response();
        response.setQuestionnaireId(questionnaireId);
        return selectAll(response);
    }
    /*
     * 提交问卷
     * */
    public void submit(Response response, List<Answer> answers){
        //response更新
        response.setSubmittedTime(LocalDateTime.now());
        response.setUpdatedTime(LocalDateTime.now());
        responseMapper.updateById(response);
        for (Answer a:answers) {
            answerService.save(a);
        }
    }
    /*
    * 修改答卷
    * */
    public void updated(Response response, List<Answer> answers){
        updateResponse(response);
        for (Answer a:answers){
            answerService.updateById(a);
        }
    }
    /*
    * 开始作答
    * */
    public Response start(Response response){
        response.setStartTime(LocalDateTime.now());
        if(getCountOfResponse(response)>0){
            response.setId(selectBy2Id(response.getUserId(),response.getQuestionnaireId()).getId());
            updateById(response);
            return response;
        }
        responseMapper.insert(response);
        QueryWrapper<Response> queryWrapper= new QueryWrapper<Response>();
        queryWrapper.eq("questionnaire_id",response.getQuestionnaireId())
                .eq("user_id",response.getUserId());
        return responseMapper.selectOne(queryWrapper);
    }
    /**
     * 新增
     */
    public void add(Response response){
        response.setSubmittedTime(LocalDateTime.now());
        response.setUpdatedTime(LocalDateTime.now());
        responseMapper.insert(response);
    }
    /**
     * 修改(根据id)
     */
    public void updateResponse(Response response){
        response.setUpdatedTime(LocalDateTime.now());
        responseMapper.updateById(response);
    }
    /*
     * 根据回答获取用户
     * */
    public User selectUser(Response response){
        return userMapper.selectById(response.getUserId());
    }

    public Response selectBy2Id(Integer userId,Integer questionnaireId){
        QueryWrapper<Response> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",userId).eq("questionnaire_id",questionnaireId);
        return responseMapper.selectOne(queryWrapper);
    }
    private Long getCountOfResponse(Response response){
        QueryWrapper<Response> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",response.getUserId())
                .eq("questionnaire_id",response.getQuestionnaireId());
        return responseMapper.selectCount(queryWrapper);
    }
    @Transactional
    public Response submitWholeResponse(Response response){
        List<Answer> answers=new ArrayList<>();
        response.setSubmittedTime(LocalDateTime.now());
        response.setUpdatedTime(LocalDateTime.now());
        if(getCountOfResponse(response)>0) {
            response.setId(selectBy2Id(response.getUserId(), response.getQuestionnaireId()).getId());

            // 根据 response ID 获取现有的答案并删除
            List<Answer> existingAnswers = getListAnswerByResponseId(response.getId());
            for (Answer answer : existingAnswers) {
                answerMapper.deleteById(answer.getId());
            }

            responseMapper.updateById(response);
            for (Answer a : response.getAnswers()) {
                a.setResponseId(response.getId());
                Question question =questionMapper.selectById(a.getQuestionId());
                if(LEVELQUESTION.getType().equalsIgnoreCase(question.getType())){//程度题
                    a.setLevel(Integer.parseInt(a.getText()));
                } else if(SORTQUESTION.getType().equalsIgnoreCase(question.getType())){//排序题
                    a.setSort(Integer.parseInt(a.getText()));
                }
                answerService.save(a);
                answers.add(a);
            }
            response.setAnswers(answers);
            return response;
        }
        else {
            response.setId(0);
            return response;
        }
    }
    public List<Answer> getListAnswerByResponseId(Integer responseId){
        QueryWrapper<Answer> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("response_id",responseId);
        return answerMapper.selectList(queryWrapper);
    }
//    public Response getWholeResponse(Integer responseId){
//
//    }
    public Response updateWholeResponse(Response response) {
        // 更新提交时间和更新时间
        response.setSubmittedTime(LocalDateTime.now());
        response.setUpdatedTime(LocalDateTime.now());

        // 根据 response ID 获取现有的答案并删除
        List<Answer> existingAnswers = getListAnswerByResponseId(response.getId());
        for (Answer answer : existingAnswers) {
            answerMapper.deleteById(answer.getId());
        }

        // 插入新的答案
        List<Answer> newAnswers = new ArrayList<>();
        for (Answer a : response.getAnswers()) {
            a.setResponseId(response.getId());
            Question question = questionMapper.selectById(a.getQuestionId());
            if (LEVELQUESTION.getType().equalsIgnoreCase(question.getType())) { // 程度题
                a.setLevel(Integer.parseInt(a.getText()));
            } else if (SORTQUESTION.getType().equalsIgnoreCase(question.getType())) { // 排序题
                a.setSort(Integer.parseInt(a.getText()));
            }
            answerService.save(a);
            newAnswers.add(a);
        }

        // 更新 response 并返回
        response.setAnswers(newAnswers);
        responseMapper.updateById(response);
        return response;
    }

    public Integer getResponseCountByQuestionId(Integer questionId){
        Questionnaire questionnaire = getQuestionnaireByQuestionId(questionId);
        List<Response> responses = getListResponseByQuestionnaireId(questionnaire.getId());
        return  responses.size();
    }
    public Questionnaire getQuestionnaireByQuestionId(Integer questionId){
        QueryWrapper<Questionnaire> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("id",questionMapper.selectById(questionId).getQuestionnaireId());
        return questionnaireMapper.selectOne(queryWrapper);
    }
    public  List<Response> getListResponseByQuestionnaireId(Integer questionnaireId){
        QueryWrapper<Response> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("questionnaire_id",questionnaireId);
        return responseMapper.selectList(queryWrapper);
    }


}
